package com.xci.platform.controller;

import com.xci.platform.core.Constant;
import com.xci.platform.helper.StringHelper;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;

import java.io.IOException;

/**
 * Web页面控制器基类
 */
public abstract class BaseController {

    /**
     * 页面重定向
     *
     * @param url 重定向的Url地址
     */
    protected String redirect(String url) {
        if (StringHelper.isEmpty(url)) {
            throw new RuntimeException("请指定重定向的Url地址");
        }
        return "redirect:" + url;
    }

    /**
     * 页面跳转
     *
     * @param url 跳转的Url地址
     */
    protected String forward(String url) {
        if (StringHelper.isEmpty(url)) {
            throw new RuntimeException("请指定跳转的Url地址");
        }
        return "forward:" + url;
    }

    protected String serverError() {
        return "_error/error500";
    }

    protected String notFound() {
        return "_error/error404";
    }

    /**
     * 标记新建记录
     *
     * @param map 模型对象
     */
    protected void createMark(ModelMap map) {
        map.put(Constant.CreateMark, "1");
    }

    /// <summary>
    /// 文件下载
    /// </summary>
    protected ResponseEntity<InputStreamResource> fileDownload(String filePath, String fileName)
            throws IOException {
        FileSystemResource file = new FileSystemResource(filePath);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }
}
